<template>
	<view class="content">
		<SearchHeader @search="onSearch">
      <template>
        <view class="main-abc">
          <view class="left">
<!--            <u-icon name="arrow-left" color="#FFFFFF" size="50"></u-icon>-->
          </view>
          <view class="center">
            <image src="/static/search/search.png" mode=""></image>
            <input type="text"  placeholder="关键字(求职意向/学历/专业）"
                   placeholder-style="{
					width: 200px;
					font-size: 26rpx;
					font-family: PingFang SC;
					font-weight: 400;
					color: #999999;
				}"
                   v-model="searchTitle"
                   @confirm="onConfirm"
            />
          </view>
          <view class="right">
            <button type="default" @click="onSearch"><text>搜索</text></button>
          </view>
        </view>
      </template>
    </SearchHeader>
    <Swiper :list="swiperList" @click="onSiperClick"></Swiper>
    <view class="content1">
      <view class="top">
        <view class="left">
          <view class="tab-1" @click="onToogle(0)">
            <text :class="active===0?'active':''">推荐</text>
            <image v-if="active===0" src="/static/index/bottom1.png" mode=""></image>
          </view>
          <view class="tab-2" @click="onToogle(1)">
            <text :class="active===1?'active':''">最新</text>
            <image v-if="active===1"src="/static/index/bottom1.png" mode=""></image>
          </view>
        </view>

        <!-- 筛选蒙层 -->
        <view>
          <Choice :list="maskList" ref="maskValue" @clear="onClear"
                  @ok="onOk"
                  @close="$refs.maskValue.mask=false"
          ></Choice>
        </view>
        <view class="right" @click="$refs.maskValue.mask=true">
          <view class="btn">
            <text>筛选</text>
            <u-icon name="arrow-down-fill" color="#323233" size="24"></u-icon>
          </view>
        </view>
        <!-- 筛选蒙层 -->

      </view>
    </view>


		<view class="h5-padding">
      <List ref="refsList" :list="getCurPageList"></List>
      <loadmore :moreObj="more"  @load="onLoadmore"></loadmore>
    </view>
		<Tabbar :current="0"></Tabbar>
	</view>
</template>

<script>
import {getResumeList,emMajorChildList} from '@/api/home'
import {emUniversityInfo,getDictItems} from '@/api/dict'
	import SearchHeader from "../../components/SearchHeader/SearchHeader.vue"
	import Swiper from "./components/Swiper.vue"
	import List from "@/components/List"
	import {emCarouselList} from '@/api/home'
  import html6 from '@/tools/amap/h5/base'
  import { mapGetters,mapActions } from 'vuex'
  import Choice from "./components/Choice";
	export default {
		components: {
			SearchHeader,
			Swiper,
			List,
      Choice
		},
		onShow() {
			uni.hideTabBar({
				animation: false
			})
		},
		data() {
			return {
        active:0,
        searchType:1,// 1.推荐 2.最新
        reParams1:{
          resumeMajor:"",
          resumeEducation:"",
          resumeExperience:""
        },
        maskList: [], //[{name:'',list:[]},{}]
        swiperList:[],//存放轮播图片
        frontAreaCode:'',
        pos:{
          //经纬度
          lng:'',
          lat:'',
        },
			}
		},
    computed:{
      ... mapGetters(['token'])
    },
    async created() {
      this.getCompanyList()
      // #ifdef  H5
      await this.h5GdMap(html6.h6AmpKey)
      // #endif
    },
		onLoad() {
      this.emCarouselList({
        type:50,
      })
		},
		methods: {
      ...mapActions(['setPosition']),
      onConfirm({detail:{value}}){
         this.searchTitle = value
        this.onReset()
        this.reParams1Value()
      },
      //点击搜索按钮
      onSearch(){
        this.onReset()
        this.reParams1Value()
      },
      reParams1Value(){
        this.getCurrentPageList(getResumeList, {
          pageNo: this.pageNo,
          searchTitle: this.searchTitle,
          searchType:this.searchType,
          ...this.reParams1
        })
      },

      //确定
      onOk(){
        this.onReset()
        let pos = {
          resumeMajor:0,//专业
          resumeEducation:'',//学历
          resumeExperience:'',//工作时间
        }
        this.maskList.map(item=>{
          const {index,list} = item
          const value = list[index] || ''
          if(item.name==='专业要求'){
            pos.resumeMajor =value?.value ?? ''
          }if(item.name==='学历要求'){
            pos.resumeEducation  =value?.value ?? ''
          }if(item.name==="工作年限"){
            pos.resumeExperience =value?.value ?? ''
          }
        })
        this.reParams1  =pos

        this.reParams1Value()
        this.$refs.maskValue.mask = false

      },
      //清空
      onClear(){
        this.maskList.map(item=>{
          if(item.index!==-1){
            item.index=-1
          }
        })
      },
      //专业根据父ID取下一级子集
      emMajorChildList(parentId = 0) {
        let list = []
        emMajorChildList({
          pageNo: 1,
          pageSize: 50,
          parentId
        }).then(res => {
          const {
            code,
            result: {
              records
            }
          } = res
          if (code === 200) {
            list = records.map(item => {
              return {
                value: item.id,
                name: item.majorName,
              }
            })
            this.maskList.unshift({
              name: '专业要求',
              list,
              index: -1
            })
          }
        }).catch(e => {

        })
      },
      //user_education学历
      async getDictItemsType(type, key = 'user_education') {
        getDictItems(key).then(res => {
          const {
            code,
            result,
            success
          } = res;
          if (success && code === 200) {
            this.getCurPageList.map(k => {
              result.map(item => {
                if ((k.resumeEducation === +item.value) || (+k
                    .resumeEducation === +item.value)) {
                  this.$set(k, 'resumeEducationValue', item.title)
                }
              })
            })

          }
        })
        this.getDictItems('user_education')
        this.getDictItems(undefined)
        this.emMajorChildList()
      },
      //获取字典中的数据
      getDictItems(scode = 'experience') {
        let key = ''
        getDictItems(scode).then(res => {
          const list = []
          const {
            code,
            result
          } = res
          if (code === 200) {
            if (scode === 'user_education') {
              key = '学历要求'
              result.map((item, index) => {
                list.push({
                  name: item.text,
                  value: item.value
                })
              })
            }
             else if (scode === 'experience') {
              key = '工作年限'
              result.map((item, index) => {
                list.push({
                  name: item.text,
                  value: item.value
                })
              })
            }
            this.maskList.push({
              name: key,
              list,
              index: -1
            })

          }
        }).catch(e => {
          console.log(e)
        })
      },
      //品质企业
      async getCompanyList() {
        const params = {
          pageNo: this.pageNo,
          searchTitle: this.searchTitle,
          searchType:this.searchType,
          ...this.reParams1
        }
        await this.getCurrentPageList(getResumeList, params)
        if (this.getCurPageList.length) {
          this.getDictItemsType ()
        }
      },
      onToogle(index){
        if(this.active===index){
          return
        }
        this.onReset()
        this.active = index
        this.searchType=index==0?1:2
        this.reParams1Value()
      },
      //h5链接地址
      async h5GdMap(key){
        function remoteLoad(url, hasCallback) {
          return createScript(url);
          /**
           * 创建script
           * @param url
           * @returns {Promise}
           */
          function createScript(url) {
            let scriptElement = document.createElement('script');
            document.body.appendChild(scriptElement);
            let promise = new Promise((resolve, reject) => {
              scriptElement.addEventListener(
                  'load',
                  e => {
                    removeScript(scriptElement);
                    if (!hasCallback) {
                      resolve(e);
                    }
                  },
                  false
              );

              scriptElement.addEventListener(
                  'error',
                  e => {
                    removeScript(scriptElement);
                    reject(e);
                  },
                  false
              );

              if (hasCallback) {
                window.____callback____ = function() {
                  resolve();
                  window.____callback____ = null;
                };
              }
            });

            if (hasCallback) {
              url += '&callback=____callback____';
            }

            scriptElement.src = url;

            return promise;
          }

          /**
           * 移除script标签
           * @param scriptElement script dom
           */
          function removeScript(scriptElement) {
            document.body.removeChild(scriptElement);
          }
        }
        // 已载入高德地图API，则直接初始化地图
        let params = {"frontAreaCode":this.frontAreaCode,"frontPublic":1}
        if (window.AMap && window.AMapUI) {
          this.getGeolocation();
        } else {
          await remoteLoad(
              `https://webapi.amap.com/maps?v=1.4.4&key=${key}&plugin=AMap.Geocoder,AMap.PlaceSearch,AMap.ToolBar`);
          await remoteLoad('https://webapi.amap.com/ui/1.0/main.js');
          this.getGeolocation();
        }
      },
      //h5定位
      getGeolocation(){
        let AMapUI = (this.AMapUI = window.AMapUI);
        let AMap = (this.AMap = window.AMap);
        let that = this;
        AMap.plugin('AMap.Geolocation', function() {
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            maximumAge: 0,           //定位结果缓存0毫秒，默认：0
            convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: true,        //显示定位按钮，默认：true
            buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy:true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
          });

          geolocation.getCurrentPosition();
          if(that.frontAreaCode==undefined || that.frontAreaCode=='')
          {
            AMap.event.addListener(geolocation, 'complete', onComplete);
          }

          function onComplete (data) {
            const {position:{lng,lat}} = data
            that.pos = {
              lat,lng
            }
            that.setPosition({
              latitude:lat, longitude:lng
            })
          }
        });
      },
      //点击轮播列表数据
      onSiperClick(item){
        console.log ( item )
      },
      //轮播图-分页列表查询
      emCarouselList(params){
        const param={
          pageNo:this.pageNo,
          pageSize:this.pageSize,
          ...params
        }
        emCarouselList(param).then(res=>{
          const {result:{records:array},code} = res
          if(code===200){
            let list = []
            array.map(item=>{
              const {id,imageUrl,title,url}=item
              if(!imageUrl.split('').includes(',')){
                list.push({
                  id,title,url,
                  img:this.$isHttp(imageUrl.split('').join(''))
                })
              } else {
                imageUrl.split(',').map(items=>{
                  list.push({
                    id,title,url,
                    img:this.$isHttp(items)
                  })
                })

              }
            })
           this.swiperList = list
          }
        }).catch(e=>{
          console.log ( e )
        })
      },
      //加载更多
      onLoadmore() {
        this.pageNo++
        this.reParams1Value()
      }
		}
	}
</script>

<style lang="scss" scoped>
.main-abc{
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 20rpx 24rpx;
  .left{

  }
  .center{
    display: flex;
    align-items: center;
    flex-basis: 78%;
    height: 58rpx;
    background: #FFFFFF;
    border-radius: 30rpx;
    image{
      margin: 20rpx;
      width: 34rpx;
      height: 34rpx;
    }

  }
  .right{
	  margin-left: 10rpx;
    width: 130rpx;
    height: 58rpx;
    button{
      position: relative;
      padding: 0;
      height: 100%;
      border-radius: 30rpx;
      background: #FFFFFF;
      text{
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        border-radius: 4rpx;
        font-size: 26rpx;
        color: #5BC4A7;
      }
    }
  }
}
.top {
  margin: 0 10rpx 30rpx 0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    display: flex;

    .active {
      font-size: 32rpx;
      font-family: PingFang SC;
      font-weight: bold;
      color: #53BAB0;
    }

    text {
      font-size: 32rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #323233;
    }

    .tab-1,.tab-2  {
      display: flex;
      flex-direction: column;
      align-items: center;


    }

    .tab-2 {
      margin-left: 30rpx;
    }
    .tab-1,.tab-2{
      image {
        width: 40rpx;
        height: 20rpx;
      }
    }
  }

  .right {
    text-align: center;

    .btn {
      width: 100rpx;
      height: 50rpx;
      line-height: 50rpx;
      background: #F0F0F0;
      border-radius: 10rpx;

      text {
        margin-right: 4rpx;
        font-size: 26rpx;
        font-family: PingFang SC;
        font-weight: 500;
        color: #323233;
      }
    }
  }
}
.content1{
  padding: 10rpx 30rpx 0 30rpx;
}
</style>
